package com.eastfair.pay.service.impl;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import com.eastfair.pay.dao.TransactionMapper;
import com.eastfair.pay.dto.TransactionDTO;
import com.eastfair.pay.dto.TransactionPageQuery;
import com.eastfair.pay.entity.Transaction;
import com.eastfair.pay.service.TransactionService;
import com.eastfair.pay.vo.TransactionStatisticsVO;
import com.eastfair.pay.vo.TransactionVO;
import com.eastfair.venueservice.entity.CreatCode;
import io.seata.common.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
* <p>
    * 业务实现类
    * 交易记录
    * </p>
*
* @author clm
* @date 2023-02-13
*/
@Slf4j
@Service
public class TransactionServiceImpl extends SuperServiceImpl<TransactionMapper, Transaction> implements TransactionService {

    private static final String TRANSACTION_NUM_FIELD = "transaction_num";

    private static final int TRANSACTION_NUM_LENGTH = 5;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
    */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<Transaction> modelList) {
    modelList.stream().forEach(s -> {
    s.setIsDeleted(BusinessConstant.YES);
    });
    // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
    return R.successDef();
    }

    /**
     * 基础数据
     * @param model
     * @return
     */
    @Override
    protected R<Boolean> handlerSave(Transaction model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTenantId(ContextUtil.getTenantId());
        //雪花ID
        return R.successDef();
    }

    /**
    * 通用查询
    *
    * @param modelDTO DTO
    * @param ids 主键id集合
    * @return list
    */
    @Override
    public List<Transaction> list(TransactionDTO modelDTO, List<Long> ids) {
        return ((TransactionService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids 主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
       magic = @Magic(
       key = "{"+
       "{'isEnabled', #args[0]?.isEnabled},"+
       "{'transactionNum', #args[0]?.transactionNum},"+
       "{'exhibitionName', #args[0]?.exhibitionName},"+
       "{'exhibitionId', #args[0]?.exhibitionId},"+
       "{'spaceName', #args[0]?.spaceName},"+
       "{'siteName', #args[0]?.siteName},"+
       "{'serviceProviderType', #args[0]?.serviceProviderType},"+
       "{'serviceProviderName', #args[0]?.serviceProviderName},"+
       "{'serviceProviderId', #args[0]?.serviceProviderId},"+
       "{'orderType', #args[0]?.orderType},"+
       "{'orderNum', #args[0]?.orderNum},"+
       "{'orderAmount', #args[0]?.orderAmount},"+
       "{'orderTime', #args[0]?.orderTime},"+
       "{'transactionType', #args[0]?.transactionType},"+
       "{'payer', #args[0]?.payer},"+
       "{'payType', #args[0]?.payType},"+
       "{'transactionState', #args[0]?.transactionState},"+
       "{'systemScene', #args[0]?.systemScene},"+
        "{'id', #args[1]}"+
        "}"))
    public List<Transaction> listOfCache(TransactionDTO modelDTO, List<Long> ids) {
       //查询
        Transaction queryModel = new Transaction();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO,queryModel);
        }
        QueryWrap<Transaction> wrapper = Wraps.q(queryModel);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(Transaction::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(Transaction::getIsDeleted, BusinessConstant.DELETE_NO);
        List<Transaction> modelList = list(wrapper);
        return modelList;
    }

    /**
     * @param transactionDTO
     * @return void
     * @Author clm
     * @Description //保存更新
     * @Date 16:48 2023/2/13
     * @Param [transactionDTO]
     */
    @Override
    public void saveOrUpdate(TransactionDTO transactionDTO) {

        Transaction transaction = new Transaction();
        BeanUtils.copyProperties(transactionDTO,transaction);

        saveOrUpdate(transaction);
    }

    /**
     * @param params
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.eastfair.pay.vo.TransactionVO>
     * @Author clm
     * @Description //交易记录分页查询
     * @Date 17:11 2023/2/13
     * @Param [params]
     */
    @Override
    public Page<TransactionVO> queryList(PageParams<TransactionPageQuery> params) {

        TransactionPageQuery transactionPageQuery = params.getModel();
        List<String> scenes = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(transactionPageQuery.getSystemScene())){
            scenes.addAll(transactionPageQuery.getSystemScene());
        } else {
            scenes.add(ContextUtil.getSystemScene());
        }
        LambdaQueryWrapper<Transaction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(transactionPageQuery.getOrderType()),Transaction::getOrderType, transactionPageQuery.getOrderType());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(transactionPageQuery.getTransactionType()), Transaction::getTransactionType, transactionPageQuery.getTransactionType());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(transactionPageQuery.getTransactionState()), Transaction::getTransactionState, transactionPageQuery.getTransactionState());
        lambdaQueryWrapper.eq(Objects.nonNull(transactionPageQuery.getExhibitionId()), Transaction::getExhibitionId, transactionPageQuery.getExhibitionId());
        lambdaQueryWrapper.in(Transaction::getSystemScene, scenes);
        lambdaQueryWrapper.like(StrUtil.isNotBlank(transactionPageQuery.getTransactionNum()), Transaction::getTransactionNum, transactionPageQuery.getTransactionNum());
        lambdaQueryWrapper.like(StrUtil.isNotBlank(transactionPageQuery.getExhibitionName()), Transaction::getExhibitionName, transactionPageQuery.getExhibitionName());
        lambdaQueryWrapper.like(StrUtil.isNotBlank(transactionPageQuery.getOrderNum()), Transaction::getOrderNum, transactionPageQuery.getOrderNum());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(transactionPageQuery.getOrderType()), Transaction::getOrderType, transactionPageQuery.getOrderType());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(transactionPageQuery.getPayType()), Transaction::getPayType, transactionPageQuery.getPayType());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(transactionPageQuery.getOrderType()), Transaction::getOrderType, transactionPageQuery.getOrderType());
        lambdaQueryWrapper.and(StrUtil.isNotBlank(transactionPageQuery.getKeyWords()),
                wrapper -> {wrapper
                        .or().or(wrapper_1 -> wrapper_1.func(it -> {it.like(Transaction::getTransactionNum, transactionPageQuery.getKeyWords()); }))
                        .or().or(wrapper_1 -> wrapper_1.func(it -> {it.like(Transaction::getExhibitionName, transactionPageQuery.getKeyWords());}))
                        .or().or(wrapper_1 -> wrapper_1.func(it -> {it.like(Transaction::getServiceProviderName, transactionPageQuery.getKeyWords());}))
                        .or().or(wrapper_1 -> wrapper_1.func(it -> {it.like(Transaction::getPayer, transactionPageQuery.getKeyWords());}))
                        .or().or(wrapper_1 -> wrapper_1.func(it -> {it.like(Transaction::getSpaceName, transactionPageQuery.getKeyWords());}))
                        .or().or(wrapper_1 -> wrapper_1.func(it -> {it.like(Transaction::getSiteName, transactionPageQuery.getKeyWords());}));

        });

        Page<Transaction> buildPage = params.buildPage();
        Page<Transaction> queryPage = page(buildPage, lambdaQueryWrapper);
        Page<TransactionVO> transactionVOPage = ConvertUtil.convertPage(queryPage, TransactionVO.class);
        return transactionVOPage;
    }

    /**
     * @return java.util.List<com.eastfair.pay.vo.TransactionStatisticsVO>
     * @Author clm
     * @Description //交易记录 统计
     * @Date 9:32 2023/2/16
     * @Param [params]
     * @param param
     */
    @Override
    public List<TransactionStatisticsVO> getTransactionStatisticsInfo(TransactionDTO param) {
        param.setSystemScene(ContextUtil.getSystemScene());
        Transaction transaction =new Transaction();
        BeanUtils.copyProperties(param,transaction);
        return baseMapper.getTransactionStatistics(transaction);
    }

    /**
     * @param transactionDTO
     * @return void
     * @Author clm
     * @Description //保存
     * @Date 14:12 2023/2/17
     * @Param [transactionDTO]
     */
    @Override
    public void save(TransactionDTO transactionDTO) {
        if (StrUtil.isBlank(transactionDTO.getTransactionNum())) {
            // 生成订单号
            String prefix = LocalDateTimeUtil.format(LocalDate.now(), "yyyyMMdd");
            String transactionNum = CreatCode.creatCode(baseMapper, TRANSACTION_NUM_FIELD, TRANSACTION_NUM_LENGTH, prefix);
            transactionDTO.setTransactionNum(transactionNum);
        }

        Transaction transaction = new Transaction();
        BeanUtils.copyProperties(transactionDTO,transaction);
        save(transaction);
    }

    /**
     * @param transactionDTO
     * @return void
     * @Author clm
     * @Description //更新
     * @Date 14:12 2023/2/17
     * @Param [transactionDTO]
     */
    @Override
    public void updateById(TransactionDTO transactionDTO) {
        Transaction transaction = new Transaction();
        BeanUtils.copyProperties(transactionDTO,transaction);
        updateById(transaction);
    }

    /**
     * @param transactionDTO
     * @return com.eastfair.pay.vo.TransactionVO
     * @Author clm
     * @Description //按条件获取交易记录
     * @Date 16:32 2023/2/20
     * @Param [transactionDTO]
     */
    @Override
    public List<TransactionVO> getTransactionStatistics(TransactionDTO transactionDTO) {
        LambdaQueryWrapper<Transaction> query = new LambdaQueryWrapper<>();
        query.eq(StrUtil.isNotBlank(transactionDTO.getOrderNum()), Transaction::getOrderNum, transactionDTO.getOrderNum());
        query.eq(transactionDTO.getId() != null, Transaction::getId, transactionDTO.getId());
        List<Transaction> transactions = baseMapper.selectList(query);
        List<TransactionVO> transactionVOs = ConvertUtil.convertList(transactions, TransactionVO.class);
        return transactionVOs;
    }


    /**
     * do转vo
     * @param model model
     * @return modelVo
     */
    @Override
    public TransactionVO doToVo(Transaction model) {
        TransactionVO modelVo = new TransactionVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }
    /**
     * do转vo
     * @param modelList modelList
     * @return list
     */
     @Override
     public List<TransactionVO> doToVos(List<Transaction> modelList) {
        if (modelList == null || modelList.isEmpty()) {
        return null;
        }
        List<TransactionVO> result = new ArrayList<>();
        for (Transaction model : modelList) {
           result.add(doToVo(model));
        }
        return result;
    }
}
